package com.cysion.study.widget;

import android.content.Context;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;


/**
 * 圆角ImageView
 * Created by moshouguan on 2015/12/23.
 */
public class RoundRectImageView extends android.support.v7.widget.AppCompatImageView {
    private Paint paint;

    public RoundRectImageView(Context context) {
        super(context);
        paint = new Paint();
    }

    public RoundRectImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
    }

    public RoundRectImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint = new Paint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        setMeasuredDimension(widthMeasureSpec,widthMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(Color.parseColor("#e5e5e5"));
        paint.setAntiAlias(true);
        paint.setStrokeWidth(4);
        paint.setStyle(Paint.Style.STROKE);
        final Rect rect = new Rect(0, 0, getWidth(), getHeight());
        final RectF rectF = new RectF(rect);
        canvas.drawRoundRect(rectF, getWidth() / 20, getWidth() / 20, paint);
        Drawable drawable = getDrawable();
        if (drawable != null) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            bitmap = ImageUtils.zoomBitmap(bitmap, getWidth(), getHeight());
            Bitmap b = BitmapUtil.getRoundedCornerBitmap(bitmap, getWidth() / 20);
            Rect scr = new Rect(0, 0, b.getWidth(), b.getHeight());
            Rect rectDest = new Rect(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), getHeight() - getPaddingBottom());
            paint.setAntiAlias(true);
            canvas.drawBitmap(b, scr, rectDest, paint);
        } else {
            super.onDraw(canvas);
        }

    }

}
